package com.promise.jokerdream.work.signin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryOddEvenResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import kotlin.random.Random

// 猜单双工作
class OddEvenWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "猜单双"

    override val isActWork: Boolean
        get() = true

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询猜单双信息
            val queryResult = gameApi.queryOddEven()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    processOddEven(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 处理猜单双逻辑
     */
    private suspend fun processOddEven(initialResponse: QueryOddEvenResponse): WorkResult {
        var currentResponse = initialResponse
        
        // 使用while循环，直到status为1为止
        while (currentResponse.status != 1) {
            // 随机猜数字，1为单，2为双
            val guessValue = Random.nextInt(1, 3) // 生成1或2
            val guessResult = gameApi.guessOddEven(guessValue)
            
            val result = guessResult.foldWithApiException(
                onSuccess = { guessResponse ->
                    currentResponse = guessResponse
                    historyManager.addHistory(name, guessResponse.getDescription())
                    null // 继续循环
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
            
            // 如果API调用失败，直接返回失败结果
            if (result != null) {
                return result
            }
        }
        
        // status为1，游戏结束
        return WorkResult.Success
    }
}